package com.ctsi.commons.event.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 一个模块发布,和监听的事件
 * 
 * @author zhangjw
 * 
 */
public class EventModule implements Serializable {

	private static final Logger log = LoggerFactory.getLogger(EventModule.class);

	private final List<Event> eventList = new ArrayList<Event>();

	private final List<EventSource> eventSourceList = new ArrayList<EventSource>();

	private String moduleId;
	private String modileName;
	private boolean enable = true;

	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	public EventModule(String moduleId, String moduleName) {
		assert (moduleId != null);
		this.moduleId = moduleId;
		this.modileName = moduleName;
	}

	public List<Event> getEventList() {
		return Collections.unmodifiableList(eventList);
	}

	public synchronized void addEvent(Event event) {
		event.setModuleId(moduleId);
		if (eventList.contains(event)) {
			log.warn("duplicate  id {} ,event id:{}", event.getId(),event.getEventid());
			return;
		}
		eventList.add(event);
	}
	public synchronized boolean containEvent(Event event){
		return eventList.contains(event);
	}

	public List<EventSource> geteventSourceList() {
		return Collections.unmodifiableList(eventSourceList);
	}

	synchronized void addEventSource(EventSource event) {
		event.setModuleId(moduleId);
		eventSourceList.add(event);
	}

	public boolean contains(EventSource event) {
		return eventSourceList.contains(event);
	}

	/**
	 * 是否发布某个事件
	 * 
	 * @param eventId
	 * @return
	 */
	public boolean containEventSource(String eventId) {
		EventSource event = new EventSource(eventId);
		return eventSourceList.contains(event);
	}

	void addAllEvent(List<Event> eventList) {
		eventList.addAll(eventList);
	}

	public String getModuleId() {
		return moduleId;
	}

	public void setModuleId(String moduleId) {
		this.moduleId = moduleId;
	}

	public String getModileName() {
		return modileName;
	}

	public void setModileName(String modileName) {
		this.modileName = modileName;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (!(obj instanceof EventModule) || moduleId == null) {
			return false;
		}
		return moduleId.equals(((EventModule) obj).moduleId);
	}

	@Override
	public int hashCode() {
		return moduleId == null ? super.hashCode() : moduleId.hashCode();
	}

	@Override
	public String toString() {
		return moduleId + ":" + modileName;
	}
}
